<template>
  <el-container class="article-container">
    <el-header height="100%">
      <div class="head-wrapper">
        <h1>{{ articleInfo.title }}</h1>
        <div class="article-info">
          <i class="el-icon-user"
          >作者：{{ articleInfo.authorName }}</i
          >
          <i class="el-icon-folder-opened"
          >类型：{{ articleInfo.type }}</i
          >
        </div>

        <div class="good">
          <span v-show="showIcon">
            <el-button
              @click="praise(articleId)"
              type="text"
              style="padding-right: 0.1rem"
            ><a-icon type="heart"
            /></el-button>
            已经有 {{ articleInfo.likeCount }} 赞</span
          >
          <span v-show="!showIcon"
          ><el-button @click="delPraise(articleId)" type="text"
          ><a-icon
            type="heart"
            theme="twoTone"
            two-tone-color="#eb2f96"/></el-button
          >已经有 {{ articleInfo.likeCount }} 赞</span
          >
        </div>
      </div>
    </el-header>
    <el-container>
      <el-container>
        <el-main>
          <div class="article-wrapper">
            <div v-html="articleInfo.content" style="margin: 30px"></div>
          </div>
          <!-- //TODO 文章评论的样式修改 -->
          <div class="comment-wrapper">
            <div class="comment-content">
              <!--          <h6 class="c-c-content c-infor-title" id="i-art-comment">-->
              <!--            <span class="commentTitle">文章评论</span>-->
              <!--          </h6>-->

              <section
                class="no-data-wrap"
                v-show="commentAndUserList.length == 0"
              >
                <em class="icon30 no-data-ico">&nbsp;</em>
                <span class="c-666 fsize14 ml10 vam"
                >该文章还没有评论，赶紧发表第一个评论吧</span
                >
              </section>
              <div
                v-for="(item, index) in currentPageData"
                :key="index"
                style="font-size: 15px"
                class="comments-item"
              >
                <div class="comments-info">
                  <div class="commenter-info">
                    <el-avatar
                      icon="el-icon-user-solid"
                      :size="60"
                      shape="circle"
                      :src="item.avatar"
                      fit="fill"
                    ></el-avatar>
                    <span style="color: #2d9aff"> {{ item.nickname }} </span>
                    <el-divider direction="vertical"></el-divider>
                    <span style="margin-left: 5px"> {{ item.content }}</span>
                  </div>
                  <div slot="action" class="action">
                    <el-button
                      type="text"
                      @click="showCommentInput(item)"
                      class="el-icon-message"
                    >
                      回复
                    </el-button>
                    <div class="el-icon-date">
                      {{ momentFormat(item.createTime) }}
                    </div>
                  </div>
                </div>

                <div v-show="item.childList" class="reply">
                  <list
                    :list="item.childList"
                    :comment="item"
                    v-on:showCommentInput="showCommentInput"
                  ></list>
                </div>
              </div>
              <footer v-show="commentAndUserList.length > 0">
                <div class="paging">
                  <a type="primary" plain @click="prevPage()"> < </a>
                  <a
                    v-for="n in totalPage"
                    :key="n"
                    :class="{
                      current: page == n,
                      undisable: page == n,
                    }"
                    :title="'第' + n + '页'"
                    href="#"
                    @click.prevent="currentPage(n)"
                  >{{ n }}</a
                  >
                  <a type="primary" plain @click="nextPage()"> > </a>
                  <span>第{{ page }}页/共{{ totalPage }}页</span>
                </div>
                <!--          <div class="comment-page">-->
                <!--            <el-pagination-->
                <!--              background-->
                <!--              :hide-on-single-page="true"-->
                <!--              layout="prev, pager, next"-->
                <!--              :page-count="totalPage"-->
                <!--              :current-page="page"-->
                <!--              @prev-click="prevPage"-->
                <!--              @next-click="nextPage"-->
                <!--            >-->
                <!--            </el-pagination>-->
                <!--          </div>-->
              </footer>
              <div id="target">
                <section class="lh-bj-list pr mt20 replyhtml">
                  <ul>
                    <li class="unBr">
                      <aside class="noter-pic">
                        <img
                          width="50"
                          height="50"
                          class="picImg"
                          src="~/assets/img/avatar-boy.gif"
                        />
                      </aside>
                      <div class="of">
                        <section class="n-reply-wrap">
                          <fieldset>
                            <textarea
                              name=""
                              v-model="comment.content"
                              :placeholder="placeholders"
                              id="commentContent"
                            ></textarea>
                          </fieldset>
                          <p class="of mt5 tar pl10 pr10">
                            <span class="fl"
                            ><tt
                              class="c-red commentContentmeg"
                              style="display: none"
                            ></tt
                            ></span>
                            <el-button @click="cancel" round>清空</el-button>
                            <el-button
                              type="primary"
                              @click="addComment()"
                              icon="el-icon-message"
                              round
                            >回复
                            </el-button>
                          </p>
                        </section>
                      </div>
                    </li>
                  </ul>
                </section>
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
      <el-aside
        width="300px"
        style="background-color: rgb(238, 241, 246); padding-left: -10px"
      >
        <a-list item-layout="horizontal" :data-source="articles">
          <a-list-item slot="renderItem" slot-scope="item">
            <a-card hoverable style="width: 300px">
              <a slot="cover" :href="'/article/' + item.id">
                <img
                  :src="item.cover"
                  :alt="item.title"
                  height="200px"
                  width="100%"
                />
              </a>

              <a-card-meta
                :description="articleInfo.authorName"
              >
                <template slot="title">
                  <a :href="'/article/' + item.id" :title="item.title">{{
                      item.title
                    }}</a>
                </template>
                <a-avatar
                  slot="avatar"
                  :src="articleInfo.avatar"
                >
                </a-avatar>
              </a-card-meta>
            </a-card>
          </a-list-item>
        </a-list>
      </el-aside>
    </el-container>
    <div>
      <a-back-top/>
    </div>
  </el-container>
</template>

<script>
import articleApi from "@/api/article";
import commentApi from "@/api/comment";
import cookie from "js-cookie";
import "@/assets/css/article.less";
import "@/assets/css/github.css";
import messageApi from "@/api/message";
import moment from "moment";

export default {
  //params.id获取路径id值
  asyncData({params, error}) {
    return {
      articleId: params.id,
    };
  },

  data() {
    return {

      commentAndUserList: [],
      currentPageData: [], //当前页显示内容
      totalPage: 1, // 统共页数，默认为1
      placeholders: "写下你的评论",
      page: 1,
      limit: 4,
      comment: {
        content: "",
        relatedId: "",
        parentId: "0",
      },
      userInfo: {
        id: "",
        nickname: "",
      },
      tagList: [], // 分类列表
      memberList: [], //会员列表
      articleInfo: {},
      articles: [],
      showIcon: true,
      message: {
        content: "",
        memberId: "0",
        senderName: "",
        link: "",
        type: 0,
      },
    };
  },
  created() {
    this.init();
    this.lookArticle();
    this.initComment();
  },
  methods: {
    //浏览量统计
    lookArticle() {
      let uid = "";
      if (this.userInfo.id === "") uid = "visitor";
      else uid = this.userInfo.id;
      articleApi.calViewCount(this.articleId, uid).then((response) => {
        console.log("增加浏览量");
      });
    },
    //浏览历史统计
    collectData() {
      if (this.userInfo.id !== "") {
        this.history.userId = this.userInfo.id
        this.history.title = this.articleInfo.title
        this.history.cover = this.articleInfo.cover
        this.history.urlPath = this.getUrlRelativePath()
        this.history.tag = "文章-" + this.articleInfo.type
        historyApi.collectHistory(this.history).then(res => {
          console.log("记录浏览历史");
        })
      }
    },
    //获取相对路径
    getUrlRelativePath() {
      const url = document.location.toString();
      const arrUrl = url.split("//");

      const start = arrUrl[1].indexOf("/");
      let relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符

      if (relUrl.indexOf("?") != -1) {
        relUrl = relUrl.split("?")[0];
      }
      return relUrl;
    },

    //初始化数据
    init() {
      this.initUserInfo();
      this.initArticle();
      this.initArticles();
      this.getLikeState();
    },
    initArticles() {
      articleApi.getAllArticle().then((response) => {
        this.articles = response.data.data.articles;
      });
    },
    initUserInfo() {
      //从cookie获取用户信息
      const userStr = cookie.get("dhu_ucenter");
      // 把字符串转换json对象(js对象)
      if (userStr) {
        this.userInfo = JSON.parse(userStr);
      }
      console.log(this.userInfo.id);
    },
    initArticle() {
      articleApi.getArticleInfo(this.articleId).then((response) => {
        this.articleInfo = response.data.data.article;
      });
    },
    //点赞
    praise(id) {
      articleApi
        .chooseLike(id)
        .then((response) => {
          if (response.data.success) {
            this.$message.success("👍点赞成功");
            this.message.senderName = this.userInfo.nickname;
            this.message.type = 2;
            this.message.link = this.articleId;
            this.message.memberId = this.articleInfo.authorId;
            messageApi.messageNotify(this.message).then((response) => {
            });
            this.message.link = "";
            this.message.memberId = "";
            this.showIcon = !this.showIcon;
            this.init();
            //window.location.reload()
          }
        })
        .catch((err) => console.log(err));
    },
    //取消前端
    delPraise(id) {
      articleApi
        .cancelLike(id)
        .then((response) => {
          this.showIcon = !this.showIcon;
          this.init();
          //window.location.reload()
        })
        .catch((err) => console.log(err));
    },
    //获取点赞状态
    getLikeState() {
      articleApi
        .getLikeState(this.articleId)
        .then((response) => {
          this.showIcon = !response.data.data.state;
          console.log(this.showIcon);
        })
        .catch((err) => console.log(err));
    },
    initComment() {
      commentApi.getArticlePageList(this.articleId).then((response) => {
        this.commentAndUserList = response.data.data.list;
        this.totalPage = Math.ceil(this.commentAndUserList.length / this.limit);
        this.totalPage = this.totalPage == 0 ? 1 : this.totalPage;
        this.setCurrentPageData();
      });
    },
    addComment() {
      this.comment.relatedId = this.articleId;
      this.message.content = this.comment.content;
      this.message.senderName = this.userInfo.nickname;
      commentApi.addArticleComment(this.comment).then((response) => {
        if (response.data.success) {
          this.$message.success("评论成功");
          if (this.comment.parentId != "0") {
            //没有父评论，不回复
            this.message.type = 1;
          } else {
            this.message.type = 0;
            this.message.link = this.articleId;
            this.message.memberId = this.articleInfo.authorId;
          }
          messageApi.messageNotify(this.message).then((response) => {
          });
          this.message.link = "";
          this.message.memberId = "0";
          this.comment.content = "";
          this.placeholders = "写下你的评论";
          if (
            this.commentAndUserList.length % 4 == 0 &&
            this.commentAndUserList.length != 0 &&
            this.comment.parentId == "0"
          )
            this.page = this.totalPage + 1;
          else if (this.comment.parentId == "0") this.page = this.totalPage;
          this.comment.parentId = "0";
          this.initComment();
        }
      });
    },
    setCurrentPageData() {
      let begin = (this.page - 1) * this.limit;
      let end = this.page * this.limit;
      this.currentPageData = this.commentAndUserList.slice(begin, end);
    },
    currentPage(val) {
      this.page = val;
      this.setCurrentPageData();
    },
    prevPage() {
      console.log("debug  page: " + this.page);
      if (this.page == 1) return;

      this.page--;
      this.setCurrentPageData();
    },
    // 下一页
    nextPage() {
      if (this.page == this.totalPage) return;

      this.page++;
      this.setCurrentPageData();
    },
    cancel() {
      this.comment.content = "";
      this.placeholders = "写下你的评论";
      this.comment.parentId = "0";
      this.message.memberId = "0";
    },
    showCommentInput(reply) {
      if (reply) {
        this.placeholders = "@" + reply.nickname + " ";
      } else {
        this.inputComment = "";
      }
      //当点击了回复时，页面滚动到评论框的位置
      document.getElementById("target").scrollIntoView();
      this.comment.parentId = reply.id;
      this.message.memberId = reply.memberId;
    },
    momentFormat(dateStr) {
      return moment(new Date(dateStr)).startOf('millisecond').fromNow()
    }
  },
};
</script>

<style scoped>
.icons-list >>> .anticon {
  margin-right: 6px;
  font-size: 24px;
}
</style>
